<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>waterfall</title>
    <style>
        .block-wrap {
            display: none;
        }
        .block {
            width: 200px;
            border: 1px solid blue;
        }
        #water {
            position: relative;
        }
    </style>
    <script src="jquery-1.7.1.js"></script>
    <script>
        var min = function (arr) {
            var index = 0;
            var m = arr[0];
            for (var i = 0; i < arr.length; i++) {
                if (arr[i] < m) {
                    m = arr[i];
                    index = i;
                }
            }
            return index;
        };

        var waterfall = function (target, block, column, width) {
            var height = column;

            jQuery(block).each(function () {
                var index = min(height);
                var left = index * width;
                var top = height[index];

                height[index] += jQuery(this).height();
                jQuery(this).css({
                    position: 'absolute',
                    left: left + 'px',
                    top: top + 'px'
                }).appendTo($(target));
            });
        };

        jQuery(function() {
            waterfall('#water', '.block', [0, 0, 0], 200);
        });

    </script>
</head>
<body>
    <div class="block-wrap">
        <div class="block" style="height: <?php echo rand(50, 300) ?>px;"></div>
        <div class="block" style="height: <?php echo rand(50, 300) ?>px;"></div>
        <div class="block" style="height: <?php echo rand(50, 300) ?>px;"></div>
        <div class="block" style="height: <?php echo rand(50, 300) ?>px;"></div>
        <div class="block" style="height: <?php echo rand(50, 300) ?>px;"></div>
        <div class="block" style="height: <?php echo rand(50, 300) ?>px;"></div>
        <div class="block" style="height: <?php echo rand(50, 300) ?>px;"></div>
        <div class="block" style="height: <?php echo rand(50, 300) ?>px;"></div>
        <div class="block" style="height: <?php echo rand(50, 300) ?>px;"></div>
        <div class="block" style="height: <?php echo rand(50, 300) ?>px;"></div>
        <div class="block" style="height: <?php echo rand(50, 300) ?>px;"></div>
        <div class="block" style="height: <?php echo rand(50, 300) ?>px;"></div>
        <div class="block" style="height: <?php echo rand(50, 300) ?>px;"></div>
        <div class="block" style="height: <?php echo rand(50, 300) ?>px;"></div>
        <div class="block" style="height: <?php echo rand(50, 300) ?>px;"></div>
        <div class="block" style="height: <?php echo rand(50, 300) ?>px;"></div>
        <div class="block" style="height: <?php echo rand(50, 300) ?>px;"></div>
    </div>
    <div id="water">

    </div>
</body>
</html>
